from celery import shared_task
from .models import Host, HostCountStatistics, Room
from django.utils import timezone
import datetime


@shared_task
def ping_all_hosts():
    hosts = Host.objects.all()
    for host in hosts:
        from ping3 import ping
        is_reachable = ping(host.ip_address, timeout=2) is not None
        host.is_alive = is_reachable
        host.save()
    return f"Pinged {len(hosts)} hosts"


@shared_task
def change_all_hosts_password():
    hosts = Host.objects.all()
    for host in hosts:
        host.change_password()
    return f"Changed passwords for {len(hosts)} hosts"


@shared_task
def generate_host_statistics():
    today = timezone.now().date()
    rooms = Room.objects.all()
    for room in rooms:
        host_count = Host.objects.filter(room=room).count()
        HostCountStatistics.objects.create(
            city=room.city,
            room=room,
            count=host_count,
            date=today
        )
    return f"Generated statistics for {len(rooms)} rooms"